<?php

namespace app\controllers\admin\uni\finance;

use app\controllers\admin\AdminController;
use app\models\admin_ops\AdminOpsRefill;
use app\models\order\Order;
use app\models\pay\Pay;
use app\models\user\UserCash;

class FinanceController extends AdminController
{
    // 已支付
    public function actionPay()
    {
        $sum = Pay::find()
            ->where(['status' => 1])
            ->sum('amount');

        return $this->success(['total' => floatval($sum)]);
    }

    // 已提现
    public function actionCash()
    {
        $sum = UserCash::find()
            ->where(['status' => 1])
            ->sum('amount');

        return $this->success(['total' => floatval($sum)]);
    }

    // 订单
    public function actionOrder()
    {
        $orders = Order::find()
            ->where(['!=', 'status', Order::$statusMapping['DELETE']])
            ->andWhere(['!=', 'status', Order::$statusMapping['NON_PAYMENT']])
            ->andWhere(['!=', 'status', Order::$statusMapping['CANCEL']])
            // 下面退货, 可能不需要处理
            // ->andWhere(['!=', 'status', Order::$statusMapping['REFUND']])
            ->all();

        $use_money = 0;
        $use_balance = 0;

        foreach ($orders as $order) {
            $use_balance += $order->use_balance;
            $use_money += $order->use_money;
        }

        return $this->success([
            'use_balance' => $use_balance,
            'use_money' => $use_money
        ]);
    }

    // 统计
    public function actionData()
    {
        $pay = Pay::find()
            ->select(['sum(amount) as total', 'DATE_FORMAT(create_time, "%Y-%m") as dt'])
            ->where(['status' => 1])
            ->groupBy('dt')
            ->orderBy(['dt' => SORT_DESC])
            ->asArray()
            ->all();

        $refill = AdminOpsRefill::find()
            ->select(['sum(balance) as total', 'DATE_FORMAT(create_time, "%Y-%m") as dt'])
            // ->where(['status' => 1])
            ->groupBy('dt')
            ->orderBy(['dt' => SORT_DESC])
            ->asArray()
            ->all();

        $cash = UserCash::find()
            ->select(['sum(amount) as total', 'DATE_FORMAT(create_time, "%Y-%m") as dt'])
            ->where(['status' => 1])
            ->groupBy('dt')
            ->orderBy(['dt' => SORT_DESC])
            ->asArray()
            ->all();

        $order = Order::find()
            ->select(['sum(use_balance) as b, sum(use_money) as m', 'DATE_FORMAT(create_time, "%Y-%m") as dt'])
            ->where(['!=', 'status', Order::$statusMapping['DELETE']])
            ->andWhere(['!=', 'status', Order::$statusMapping['NON_PAYMENT']])
            ->andWhere(['!=', 'status', Order::$statusMapping['CANCEL']])
            ->groupBy('dt')
            ->orderBy(['dt' => SORT_DESC])
            ->asArray()
            ->all();

        return $this->success([
            'pay' => $pay,
            'cash' => $cash,
            'order' => $order,
            'refill' => $refill,
        ]);
    }
}